<template>

  <el-card class="box-card login-card">
    <div slot="header" class="clearfix"><span>登录</span></div>

    <el-form hide-required-asterisk
             ref="loginForm"
             :model="loginForm"
             :rules="loginFormRules"
             label-width="80px"
    >
      <el-form-item label="用户名称" prop="userName">
        <el-input v-model="loginForm.userName" prefix-icon="el-icon-user"></el-input>
      </el-form-item>

      <el-form-item label="用户密码" prop="userPwd">
        <el-input v-model="loginForm.userPwd" prefix-icon="el-icon-lock" show-password></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="login('loginForm')">登录</el-button>
        <el-button @click="resetForm('loginForm')">重置</el-button>
      </el-form-item>

    </el-form>
  </el-card>

</template>
<script>

export default {
  data() {
    return {
      /* 表单数据 */
      loginForm: {
        userName: "",
        userPwd: "",
      },
      /* 表单验证 */
      loginFormRules: {
        userName: [
          {required: true, message: "请输入用户名称", trigger: "blur"},
          {min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur"},
        ],
        userPwd: [
          {required: true, message: "请输入用户密码", trigger: "blur"},
          {min: 4, max: 8, message: "长度在 4 到 8 个字符", trigger: "blur"},
        ],
      },
    };
  },
  methods: {
    /* 执行登录：收集表单数据，发送服务器端 */
    login(loginForm) {
      /*
          validate：对整个表单进行校验的方法，参数为一个回调函数，该回调函数会在校验结束后被调用
      */
      this.$refs[loginForm].validate((valid) => {
        //验证
        if (valid) {
          //true   通过基础的前端验证，收集表单数据，发送服务器端
          //警告框
          this.$axios.post('/login', this.$qs.stringify(this.loginForm)).then(resp => {
            if (resp.data.returnCode === 2000) {
              this.$router.push('/main');
            } else if (resp.data.returnCode === 4000) {
              //提示信息
              this.$message({
                message: resp.data.returnMsg,
                type: 'error'
              });
            }
          }).catch(error => {
            console.log(error);
          })
          //...
        } else {
          //false
          console.log("error submit!!");
          return false;
        }
      });
    },
    /* 重置表单数据 */
    resetForm(loginForm) {
      /* resetFields：对整个表单进行重置，将所有字段值重置为初始值并移除校验结果 */
      this.$refs[loginForm].resetFields();
    },
  },
  mounted() {
  },
};
</script>
<style>
/* 自增样式 */
.login-card {
  margin: 325px auto;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.box-card {
  width: 480px;
}
</style>